package wykop.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;

/**
 * Created by IntelliJ IDEA. User: kad Date: 05.11.11 Time: 11:52 To change this
 * template use File | Settings | File Templates.
 */
public class XmlUtils {

	private final static Logger logger = Logger.getLogger("wykop.xml.parsing");

	public static List<Node> asList(final NodeList nodeList) {
		final List<Node> list = Lists.newArrayList();
		for (int i = 0; i < nodeList.getLength(); i++) {
			list.add(nodeList.item(i));
		}
		return list;
	}

	public static Node fromHtmlFile(final File file) {
		try {
			final BufferedReader reader = new BufferedReader(new FileReader(
					file));
			return fromHtmlReader(reader);
		} catch (final Exception e) {
			logger.error("Error when parsing: " + file.getAbsolutePath(), e);
			throw new RuntimeException(e);
		}
	}

	public static Node fromHtmlReader(final Reader reader) {

		try {

			final String page = CharStreams.toString(reader);
			final InputStream temp = new ByteArrayInputStream(page.getBytes());

			final SAXBuilder saxBuilder = new SAXBuilder(
					"org.ccil.cowan.tagsoup.Parser", false);
			final org.jdom.Document jdomDocument = saxBuilder.build(temp);

			final StringWriter sw = new StringWriter();
			final XMLOutputter xmlOutputter = new XMLOutputter();
			xmlOutputter.output(jdomDocument, sw);

			final String string = sw.toString();
			final InputStream is = new ByteArrayInputStream(
					string.getBytes("utf-8"));
			return DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(is);
		} catch (final Exception e) {
			logger.error("Error when parsing reader", e);
			throw new RuntimeException(e);
		}
	}

	public static Node fromHtmlStream(final InputStream is) {
		try {
			// Tidy tidy = new Tidy();
			// Document document = tidy.parseDOM(is, new NullOutputStream());
			// return document.getDocumentElement();
			final BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			return fromHtmlReader(reader);
		} catch (final Exception e) {
			logger.error("Error when parsing stream", e);
			throw new RuntimeException(e);
		}
	}

}
